import React from 'react'
import {Icon, Menu} from 'antd'
import {Link, withRouter} from 'react-router-dom'

class LeftMenu extends React.Component{
  state = {
    selectedKey: '0'
  }
  handleClick (e) {
    this.setState({selectedKey: e.key})
  }

  componentDidMount () {
    const {location} = this.props
    this.update(location)
  }

  update (location) {
    const {sidebars} = this.props
    const index = sidebars.findIndex((item) => {
      return item.linkTo === location.pathname.match(/(^\/[\w-]*)/g)[0]
    })
    if (index < 0) return
    const newIndex = '' + index
    if (this.state.selectedKey === newIndex) return
    this.setState({
      selectedKey: newIndex
    })
  }

  render () {
    const {sidebars} = this.props
    return (
      <Menu
        mode='inline'
        selectedKeys={[this.state.selectedKey]}
        style={{height: '100%'}}
        onClick={this.handleClick.bind(this)}
      >
        {
          sidebars.map((item, key) => {
            return (
              <Menu.Item key={key}>
                <Link to={item.linkTo}>
                  {item.name}
                  <Icon type={item.icon}
                        className='margin-l-2' />
                </Link>
              </Menu.Item>)
          })
        }
      </Menu>
    )
  }
}
export default withRouter(LeftMenu)
